﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using YAFTS.Contracts;
using YAFTS.Contracts.Model;
using YAFTS.Core.Model;

namespace YAFTS.Core
{
	internal sealed class SimpleWordsReader : IWordsReader
	{
		private readonly IConfiguration _configuration;

		public SimpleWordsReader(IConfiguration configuration)
		{
			_configuration = configuration;
		}


		public HashSet<IWord> Read(TextReader reader)
		{
			return new HashSet<IWord>(ReadWords(reader).Distinct().Select(x => new Word(x)));
		}

		public bool SupportPath(string path)
		{
			return true;
		}

		private IEnumerable<string> ReadWords(TextReader reader)
		{
			var wordSize = _configuration.DefaultWordSize;
			var buffer = new char[wordSize];
			using (reader)
			{
				var ch = 0;
				while (ch != -1)
				{
					ch = reader.Read();
					if (!char.IsLetterOrDigit((char) ch))
					{
						continue;
					}

					var index = 0;
					while (ch != -1 && char.IsLetterOrDigit((char) ch))
					{
						buffer[index] = (char) ch;
						index++;
						if (index == buffer.Length)
						{
							Array.Resize(ref buffer, buffer.Length + wordSize);
						}
						ch = reader.Read();
					}

					yield return new string(buffer, 0, index);

					if (ch == -1)
					{
						yield break;
					}
				}
			}
		}
	}
}